<?php
namespace App\Repositories;

use App\Models\Coach;
use App\Models\Message;
use Carbon\Carbon;
use App\Models\Student;
use App\Models\School;

class MessageRepository extends BaseRepository
{
    public function __construct(
        Message $message
    )
    {
        $this->model = $message;
    }


    /**
     * 获取消息列表
     * @param array $data
     * @param array|string $extra
     * @param string $size
     * @return string
     */
    public function index($data, $student_id, $size = '')
    {
        $message_list = $this->model->where(['to_id' => $data['to_id'], 'to_type' => $data['to_type']])->limit($size)
                                ->offset(($data['page'] - 1) * $size)->orderBy('id', 'desc')->get();

        $rs = [];

        $rs['list'] = $message_list;
        $rs['count'] = $this->model->where(['to_id' => $data['to_id'], 'to_type' => $data['to_type']])->count();
        return $rs;
    }


    /**
     * 存储odb
     * @param $inputs
     */
    public function store($inputs, $extra = '')
    {
        $inputs['created_at'] = Carbon::now()->toDateTimeString();
        return $this->model->insert($inputs);
    }


    /**
     * 更新
     * @param $id
     * @param $input
     * @return mixed
     */
    public function update($id, $input,$extra = '')
    {
        $model = $this->getById($id);
        return $this->save($model,$input);
    }


    /**
     * 编辑特定id资源
     * @param  int $id 资源id
     * @param  string|array $extra 可选额外传入的参数
     * @return Illuminate\Support\Collection
     */
    public function edit($id, $extra)
    {

    }

    /**
     * @param $model
     * @param $inputs
     * @param bool $falg
     * @return mixed
     */
    public function save($model , $inputs , $falg = false)
    {
        return $model;
    }


    /**
     * 发送消息
     * @param $toUser
     * @param $sendUser
     * @param $content
     */
    public  function sendMsg($toUser, $sendUser, $extra = '')
    {
        //
        if($extra instanceof \App\Models\PutPeriod){

            if($sendUser instanceof \App\Models\Student){

                $this->model->from_type = 3;//来源学员
            }elseif($sendUser instanceof \App\Models\School){

                $this->model->from_type = 1;//来源驾校
            }elseif($sendUser instanceof \App\Models\Coach){

                $this->model->from_type = 2;//来源教练
            }

            $this->model->from_id = $sendUser->id;

            if($toUser instanceof \App\Models\Student){

                $this->model->to_type = 1;

                if($extra->km == 2){
                    $km = '科二实操练习';
                }else{
                    $km = '科三实操练习';
                }
                $content = '你预约了'.$extra->coach->name.'：'.date('Y-m-d H:i', $extra->start_time).' ~ '.date('H:i').'的'.$km.'，要按时到达哦';
            }
            $this->model->to_id = $toUser->id;
            $this->model->cotent = $content;
        }
    }

}